<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="../jq/jquery.js"></script>
    <link rel="stylesheet" href="../jq/bootstrap/bootstrap.min.css" />
    <script src="../jq/bootstrap/bootstrap.min.js"></script>
  </head>
  <style>
    body {
      text-align: center;
      position: relative;
    }
    #bg {
      width: 100%;
      height: 1000px;
      background: #ccc;
      opacity: 40%;
      z-index: 10;
      position: absolute;
      left: 0;
      top: 0;
      display: none;
    }
    #addGoods {
      display: none;
      position: absolute;
      left: 40%;
      top: 100px;
      width: 300px;
      height: 300px;
      border: 1px solid #ccc;
      text-align: center;
      background: #ccc;
      z-index: 20;
    }
    #add {
      width: 150px;
      height: 60px;
    }
    th,
    td {
      text-align: center;
    }
  </style>
  <body>
    <button id="add">添加商品</button>
    <table class="table" border="1" style="width: 600px; margin: 30px auto">
      <thead>
        <tr>
          <th>商品名称</th>
          <th>商品价格</th>
          <th>商品库存</th>
          <th>添加时间</th>
          <th>商品操作</th>
        </tr>
      </thead>
      <tbody id="goodsList"></tbody>
    </table>

    <table class="table" border="1" style="width: 600px; margin: 30px auto">
      <thead>
        <tr>
          <th><input type="checkbox" id="all" /> 商品名称</th>
          <th>商品价格</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="shopCarList"></tbody>
    </table>
    <div>
      <h3>总价：<span>0.00</span>￥</h3>
    </div>

    <div id="addGoods">
      <br /><br />
      商品名称：<input type="text" id="goodsName" /><br /><br />
      商品价格：<input type="text" id="goodsPrice" /><br /><br />
      商品库存：<input type="text" id="goodsStock" /><br /><br />
      <button id="saveGoods">添加</button>&nbsp;&nbsp;&nbsp;<button id="quxiao">
        取消
      </button>
    </div>
    <div id="bg"></div>
  </body>
  <script>
    var flag = 'add',
      dataIndex //新添加 false 编辑
    $(function () {
      $('#all').change(function () {
        var status = $(this).prop('checked')
        $('#shopCarList input:checkbox').prop('checked', status)

        var shopList = getLocalData('shopList')
        shopList.map(function (v, i) {
          shopList[i].status = status
        })
        localStorage.setItem('shopList', JSON.stringify(shopList))
        total()
      })

      $('#add').click(function () {
        flag = 'add'
        $('#addGoods,#bg').toggle()
      })
      $('#quxiao,#bg').click(function () {
        $('#addGoods,#bg').hide()
      })
      //添加或编辑
      $('#saveGoods').click(function () {
        var goodsName = $('#goodsName').val(),
          goodsPrice = $('#goodsPrice').val(),
          goodsStock = $('#goodsStock').val(),
          createTime = getTime()
        var goodsList = getLocalData('goodsList')
        if (flag == 'add') {
          goodsList.unshift({
            id: goodsList.length + 1,
            name: goodsName,
            price: goodsPrice,
            stock: goodsStock,
            ctime: createTime,
          })
        } else {
          goodsList[dataIndex] = {
            id: goodsList[dataIndex].id,
            name: goodsName,
            price: goodsPrice,
            stock: goodsStock,
            ctime: createTime,
          }
        }
        localStorage.setItem('goodsList', JSON.stringify(goodsList))
        showGoodsList()
      })
      showGoodsList()
      showShopCar()
    })
    function total() {
      var sum = 0
      $('#shopCarList input:checked').each(function (v) {
        sum += +$(this).attr('count')
      })
      $('span').html(sum)
    }
    //购物车列表
    function showShopCar() {
      var shopList = getLocalData('shopList')
      var str = ''
      var checkboxStatus = true
      for (let i in shopList) {
        if (shopList[i].status == false) {
          checkboxStatus = false
        }
        str += `<tr>
                    <td><input type="checkbox" ${
                      shopList[i].status ? 'checked' : ''
                    } count="${
          shopList[i].num * shopList[i].price
        }" index="${i}">${shopList[i].name}</td>
                    <td>${shopList[i].price}</td>
                    <td><button onclick=jiaAndJian('jia',${i})>+</button> ${
          shopList[i].num
        } <button onclick=jiaAndJian('jian',${i})>-</button></td>
                    <td>${shopList[i].num * shopList[i].price}</td>
                    <td><a href='#' onclick="shopDel(${i})">删除</td>
                </tr>`
      }
      $('#all').prop('checked', checkboxStatus)
      $('#shopCarList').html(str)
      $('#shopCarList input:checkbox').change(function () {
        var shopList = getLocalData('shopList')
        var index = $(this).attr('index')
        shopList[index].status = $(this).prop('checked')
        localStorage.setItem('shopList', JSON.stringify(shopList))
        showShopCar()
        total()
      })
      total()
    }
    function shopDel(index) {
      var shopList = getLocalData('shopList'), //购物车列表
        goodsList = getLocalData('goodsList')
      var num = shopList[index].num
      var res = goodsList.findIndex(function (v) {
        return v.id == shopList[index].id
      })
      if (res > -1) {
        goodsList[res].stock = goodsList[res].stock + num
        shopList.splice(index, 1)
        localStorage.setItem('shopList', JSON.stringify(shopList))
        localStorage.setItem('goodsList', JSON.stringify(goodsList))
        showShopCar()
        showGoodsList()
        total()
      }
    }
    function jiaAndJian(parms, index) {
      var shopList = getLocalData('shopList'), //购物车列表
        goodsList = getLocalData('goodsList')
      if (parms == 'jia') {
        shopList[index].num++
      } else {
        if (shopList[index].num == 1) {
          alert('至少购买一个')
          return false
        }
        shopList[index].num--
      }
      var res = goodsList.findIndex(function (v) {
        return v.id == shopList[index].id
      })

      if (res > -1) {
        if (parms == 'jia') {
          if (goodsList[res].stock == 0) {
            alert('没有库存了')
            return false
          }
          goodsList[res].stock--
        } else {
          goodsList[res].stock++
        }
        localStorage.setItem('shopList', JSON.stringify(shopList))
        localStorage.setItem('goodsList', JSON.stringify(goodsList))
        showShopCar()
        showGoodsList()
      }
    }

    function getLocalData(parms) {
      var data = localStorage.getItem(parms)
      if (data != null) {
        return JSON.parse(data)
      } else {
        return []
      }
    }
    function showGoodsList() {
      var strHtml = ''
      var goodsList = getLocalData('goodsList')
      for (let i in goodsList) {
        strHtml += `<tr>
                            <td>${goodsList[i].name}</td>
                            <td>${goodsList[i].price}</td>
                            <td>${goodsList[i].stock}</td>
                            <td>${goodsList[i].ctime}</td>
                            <td><a href="#" onclick="del(${i})">删除</a> | <a href="#" onclick=edit(${i})>编辑</a> | <a href="#" onclick="addCar(${i})">加入购物车</a></td>
                        </tr>`
      }
      $('#goodsList').html(strHtml)
    }
    function addCar(index) {
      var goodsList = getLocalData('goodsList'), //商品列表 //获取本地存储的数据
        shopList = getLocalData('shopList') //购物车列表
      goodsList[index].stock--
      var res = shopList.findIndex(function (v) {
        return v.id == goodsList[index].id
      })
      if (res > -1) {
        shopList[res].num++
      } else {
        shopList.unshift({
          name: goodsList[index].name,
          price: goodsList[index].price,
          num: 1,
          id: goodsList[index].id,
          status: false,
        })
      }

      localStorage.setItem('shopList', JSON.stringify(shopList))
      localStorage.setItem('goodsList', JSON.stringify(goodsList))
      showShopCar()
      showGoodsList()
    }

    function edit(index) {
      var goodsList = getLocalData('goodsList') //获取本地存储的数据
      $('#goodsName').val(goodsList[index].name)
      $('#goodsPrice').val(goodsList[index].price)
      $('#goodsStock').val(goodsList[index].stock)
      $('#addGoods').show()
      flag = 'edit' //把这个变量设置成
      dataIndex = index
    }
    function del(index) {
      var goodsList = getLocalData('goodsList')
      goodsList.splice(index, 1)
      localStorage.setItem('goodsList', JSON.stringify(goodsList))
      showGoodsList()
    }
    function getTime() {
      var nowTime = new Date()
      // 2022-4-11 15:24:44
      var year = nowTime.getFullYear()
      var month = nowTime.getMonth() + 1
      var days = nowTime.getDate()
      var hours = nowTime.getHours()
      var f = nowTime.getMinutes()
      var m = nowTime.getSeconds()
      return year + '-' + month + '-' + days + ' ' + hours + ':' + f + ':' + m
    }
  </script>
</html>
